import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import Cookies from "js-cookie";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/404"]; // no redirect whitelist

const redirectToHomeOrLogin = (userLevel, activityId) => {
  if (userLevel !== "/" || activityId === 0) {
    return `/home/${userLevel}/${activityId}`;
  }
};

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);

  const hasToken = store.getters.token || getToken();
  const userLevel = store.getters.userLevel || Cookies.get("level");
  const activityId = store.getters.activity_id || Cookies.get("activity_id");

  if (hasToken) {
    // 如果访问的是根路径，则重定向到 /setting
    if (["/", "/setting", "/home"].includes(to.path)) {
      next(redirectToHomeOrLogin(userLevel, activityId));
    } else if (to.path === "/login") {
      // 如果已登录且尝试访问登录页面，则重定向到相应的用户级别页面
      next(redirectToHomeOrLogin(userLevel, activityId));
    } else {
      // 检查是否已经获取了用户信息
      const hasGetUserInfo = store.getters.userInfo;
      if (!hasGetUserInfo) {
        try {
          await store.dispatch("user/getInfo");
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "请重新登录");
          next(`/login?redirect=${to.path}`);
          return; // 确保在这里返回，防止继续执行下面的 next()
        }
      }
      next(); // 只有在需要时才调用 next()
    }
  } else {
    // 如果没有token，并且不在白名单中，则重定向到登录页
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
